#include "stdSqliteDataBase.h"
#include <iostream>

// StdSqliteBase::StdSqliteBase(const std::string &name) : m_name(name)
// {
//     m_db = NULL;
// }

// StdSqliteBase::~StdSqliteBase()
// {
//     m_db = NULL;
//     sqlite3_close(m_db);
// }

bool StdSqliteBase::connect(const char * localname)
{
    int ret = sqlite3_open(localname, &m_db);
    if (ret != SQLITE_OK)
    {
        std::cout << "error :" << sqlite3_errcode(m_db) << std::endl;
        return false;
    }
    return true;
}

QueryResult StdSqliteBase::query(const std::string &sql)
{
    QueryResult result;
    char *errmsg = nullptr;
    char **dbResult = nullptr;
    int nrow = 0;
    int ncol = 0;

    int rc = sqlite3_get_table(m_db, sql.c_str(), &dbResult, &nrow, &ncol, &errmsg);
    if (rc == SQLITE_OK)
    {
        for (int i = 0; i < ncol; ++i)
        {
            result.columeName.push_back(dbResult[i]);
        }

        for (int i = 0; i < nrow; ++i)
        {
            std::vector<std::string> rowData;
            for (int j = 0; j < ncol; ++j)
            {
                rowData.push_back(dbResult[(i + 1) * ncol + j]);
            }
            result.datas.push_back(rowData);
        }

        sqlite3_free_table(dbResult);
    }
    else
    {
        std::cerr << "查询失败: " << errmsg << std::endl;
        sqlite3_free(errmsg);
    }

    return result;
}

bool StdSqliteBase::execute(const std::string &sql)
{
    int ret = sqlite3_exec(m_db, sql.c_str(), NULL, NULL, NULL);
    if (ret != SQLITE_OK)
    {
        std::cout << "error :" << sqlite3_errcode(m_db) << std::endl;
        return false;
    }
    return true;
}

void StdSqliteBase::close()
{
    sqlite3_close(m_db);
}
